// JavaScript Document
var nsid;
var nsname;
var osocialurl;
var dom_button;
var dom_div_haut;
var dom_div_bas;
var dom_content;
var htmlbas;
var htmlhaut;
var viewer;
var owner;    
var viewername;
var ownername;
var ownerid;
var viewerid;
var viewerprofile;
var viewerthumbnail;
var regExpBeginning = /^\s+/;
var regExpEnd       = /\s+$/;
var postparams = {};
var getparams = {};
var currentview;
var dom_radiobuttondiv;
var Hi5AuthToken = null;
var domain;

gadgets.util.registerOnLoadHandler(Init);
 
//debug function for testing purposes 
function debug(msg){
		debugwindow=window.open('','debug','toolbar=1,resizable=1,width=500,height=500,scrollbars=yes');
		debugwindow.document.writeln(msg+'<br>');
	} 
 
function makeCachedRequest(url, callback, params, refreshInterval) {
	debug("makeCachedRequest");
  var ts = new Date().getTime();
  var sep = "?";
  if (refreshInterval && refreshInterval > 0) {
    ts = Math.floor(ts / (refreshInterval * 1000));
  }
  if (url.indexOf("?") > -1) {
    sep = "&";
  }
  url = [ url, sep, "nocache=", ts ].join("");
  gadgets.io.makeRequest(url, callback, params);
}

function Init() {
		debug("Init");

		// Not yet used
        postparams[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.JSON;
        postparams[gadgets.io.RequestParameters.AUTHORIZATION] = gadgets.io.AuthorizationType.SIGNED;
        postparams[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.POST;

        getparams[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.JSON;
        getparams[gadgets.io.RequestParameters.AUTHORIZATION] = gadgets.io.AuthorizationType.SIGNED;
		getparams[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.GET;
 
        osocialurl='http://www.osocial.net/network/';
        osocialurldb='http://www.osocial.net/network/db/';
		osocialurlgraph='http://www.osocial.net/network/graph/springgraph/';
        
        dom_div_haut = document.createElement("div");
        dom_div_bas = document.createElement("div");
        dom_content = document.getElementById("content");
    
		domain = opensocial.getEnvironment().getDomain();
		
		currentview = gadgets.views.getCurrentView().getName();

        if (domain=="opensocket")
        {  
          nsid=4;
          nsname='Facebook';
        }		
        if (domain=="orkut.com")
        {  
          nsid=3;
          nsname='orkut';
        }
        else if (domain=="hi5.com")
        {  
          nsid=2;
          nsname='hi5';
		 }
        else if (domain=="google.com/ig")
        {  
          nsid=6;
          nsname='Google';
		 }		 
  
    document.getElementById('content').innerHTML = 'oSocial connection...';
    
	var opt_owner_params = {};
	opt_owner_params[opensocial.DataRequest.PeopleRequestFields.PROFILE_DETAILS] = [opensocial.Person.Field.PROFILE_URL]; 

    var req = opensocial.newDataRequest();
    req.add(req.newFetchPersonRequest('OWNER', opt_owner_params), 'owner');
    req.add(req.newFetchPersonRequest('VIEWER', opt_owner_params), 'viewer');
    req.send(onLoadViewerOwner);
};
  
function onLoadViewerOwner(dataResponse) {           
	debug("onLoadViewerOwner");
	
    document.getElementById('content').innerHTML='';
            
     viewer = dataResponse.get('viewer').getData();
     owner = dataResponse.get('owner').getData();
     viewername=viewer.getDisplayName();
     ownername=owner.getDisplayName();
	 
	 debug("viewername="+viewername);
	 debug("ownername="+ownername);
	 
     ownerid=owner.getField(opensocial.Person.Field.ID);
     viewerid=viewer.getField(opensocial.Person.Field.ID);   
	 
	 debug("viewerid="+viewerid);
	 debug("ownerid="+ownerid);

	 
	//if (nsid==3)
	//	viewerprofile=encodeURIComponent('http://sandbox.orkut.com'  +viewer.getField(opensocial.Person.Field.PROFILE_URL));
	//else
	viewerprofile=encodeURIComponent(viewer.getField(opensocial.Person.Field.PROFILE_URL));
	
     debug("PROFILE_URL="+viewer.getField(opensocial.Person.Field.PROFILE_URL));
	 
	 viewerthumbnail=encodeURIComponent(viewer.getField(opensocial.Person.Field.THUMBNAIL_URL));

	 debug("THUMBNAIL_URL="+viewer.getField(opensocial.Person.Field.THUMBNAIL_URL));
        
	if ((currentview=="canvas") || (currentview=="preview"))	
	{
		htmlhaut = "Hi "+viewername+",<br><br>";
		htmlbas = "<p class='noteremove'><br>Note that if you set your oSocial page to <b>Public</b> then it will be opened to the Web during 24 hours<br>but if you set it to <b>Private</b>, only you and your friends will have an access to the page with a secret link.<br>And in any cases, all your friends are kept private until they decide themself to be public.</p>";
		htmlbas +="<img src='http://www.osocial.net/network/images/osocial_graph.jpg'>";
	}
	else
	{
		htmlhaut="";                				 
		htmlbas="";                				 
	}
		
	htmlbas += "<br><p class='note'>Free and open your social graph with oSocial <img src='http://www.osocial.net/images/osocial_veryverysmall.png' border='0'></p>";
	
	if  (nsid==4)
	{
	
		htmlhaut = "Hi "+viewername+",<br>";
		htmlbas = "<p class='noteremove'><b><br>Sorry but due to a violation of Facebook Developers Terms of Service section 2.A.5 and 2.A.6, this application is currently closed.<br>We have to modify <a href='http://www.osocial.net/network'>oSocial</a> features so that Facebook TOS is not violated anymore.<br>Thank you for your understanding and sorry for the inconvenience.</b></p>";
		htmlbas +="<img src='http://www.osocial.net/network/images/osocial_graph.jpg'>";
		htmlbas += "<br><p class='note'>Free and open your social graph with <a href='http://www.osocial.net/network'>oSocial <img src='http://www.osocial.net/images/osocial_veryverysmall.png' border='0'></a></p>";

		dom_div_haut.innerHTML = htmlhaut;
		dom_content.appendChild(dom_div_haut);           
		dom_div_bas.innerHTML = htmlbas; 
		dom_content.appendChild(dom_div_bas);
		
	}
	else
	{

				 
      if (!viewer.isOwner())
      {                       
      
        makeCachedRequest(osocialurldb+'exists.php5?uid='+ownerid+'&nsid='+nsid,
        function (responseJSONowner) {                  
            
            var resultjson= responseJSONowner.data;			
            
            if (resultjson.result=='success') 
            {
			    var osocialid = resultjson.osocialid; 
                var nbfriends = resultjson.nbfriends; 
				
				if (resultjson.privacy==1)
				{
					htmlhaut += "Visit <a target='_blank' href='"+osocialurl+"id.php?id="+osocialid+"'>"+ownername+" public oSocial page</a> with "+nbfriends+" friends";
					htmlhaut += " (<a target='_blank' href='"+osocialurlgraph+"index.php?id="+osocialid+"'>visualization</a>).";
					htmlhaut += "<br><br>";
				}
				else
				{
					htmlhaut += "Visit <a target='_blank' href='"+osocialurl+"id.php?id="+osocialid+"&t="+resultjson.osocialtoken+"'>"+ownername+" private oSocial page</a> with "+nbfriends+" friends";
					htmlhaut += " (<a target='_blank' href='"+osocialurlgraph+"index.php?id="+osocialid+"&t="+resultjson.osocialtoken+"'>visualization</a>).";
					htmlhaut += "<br><br>";
				}
				
				makeCachedRequest(osocialurldb+'exists.php5?uid='+viewerid+'&nsid='+nsid,
				function (responseJSONviewer) {                  
            
					var resultjson= responseJSONviewer.data;			
            
					if (resultjson.result=='success') 
					{
						var osocialid = resultjson.osocialid; 
						var nbfriends = resultjson.nbfriends; 
				
						if (resultjson.privacy==1)
						{
							htmlhaut += "And do not forget <a target='_blank' href='"+osocialurl+"id.php?id="+osocialid+"'>your public oSocial page</a> with "+nbfriends+" friends";
							htmlhaut += " (<a target='_blank' href='"+osocialurlgraph+"index.php?id="+osocialid+"'>visualization</a>).";
							htmlhaut += "<br>";
						}
						else
						{
							htmlhaut += "And do not forget <a target='_blank' href='"+osocialurl+"id.php?id="+osocialid+"&t="+resultjson.osocialtoken+"'>your private oSocial page</a> with "+nbfriends+" friends";				
							htmlhaut += " (<a target='_blank' href='"+osocialurlgraph+"index.php?id="+osocialid+"&t="+resultjson.osocialtoken+"'>visualization</a>).";
							htmlhaut += "<br>";
						}
							
						htmlbas += "<br><p class='noteremove'>Take the control of your page, install this application and go to oSocial.</p>";
					}                          
					else if (resultjson.raison=='User not found') 
					{
						htmlbas += "<br><p class='progress'>Install this application and free your Social Graph</p>";
					}
					else
					{
						htmlhaut += "Can not check "+viewername+" profile : "+resultjson.raison+".<br><br>";
					}
					
					dom_div_haut.innerHTML = htmlhaut;
					dom_content.appendChild(dom_div_haut);           
					dom_div_bas.innerHTML = htmlbas; 
					dom_content.appendChild(dom_div_bas);
			  
				},getparams,0); 					
            }                          
			else if (resultjson.raison=='User not found')
			{
				htmlhaut += ownername+" has not yet joined oSocial<br><br>";
				dom_div_haut.innerHTML = htmlhaut;
				dom_content.appendChild(dom_div_haut);           
				dom_div_bas.innerHTML = htmlbas; 
				dom_content.appendChild(dom_div_bas);
			}
			else
			{
				htmlhaut += "Can not check "+ownername+" profile : "+resultjson.raison+".<br><br>";
				dom_div_haut.innerHTML = htmlhaut;
				dom_content.appendChild(dom_div_haut);           
				dom_div_bas.innerHTML = htmlbas; 
				dom_content.appendChild(dom_div_bas);
			}			
            
          },getparams,0);
		  
		  	if ((currentview=="canvas") || (currentview=="preview"))	
				gadgets.window.adjustHeight(500);
			else
				gadgets.window.adjustHeight(150);
		                   
        }
        else
        {
            CheckOwner();            
        }
     }               
}



function CheckOwner() {           
	  debug("CheckOwner");

      try{
        dom_button = document.createElement('<button class="submitButton"/>');
      }catch(err){
		dom_button = document.createElement("button");
		dom_button.setAttribute('class','submitButton');
	}		
	
      makeCachedRequest(osocialurldb+'exists.php5?uid='+ownerid+'&nsid='+nsid, 
      function (responseJSON) {         

     var resultjson= responseJSON.data;                                         
            
     if (resultjson.result=='success') 
     {
	 	var osocialid = resultjson.osocialid; 
        var nbfriends = resultjson.nbfriends; 
		var osocialtoken = resultjson.osocialtoken; 
		var privacy = resultjson.privacy; 
		var registered = resultjson.registered;
		var htmlhautcheck;
		
		if (registered==0)
		{		
			if (resultjson.privacy==1) 
			{
					htmlhautcheck = htmlhaut + "You have already an oSocial page with "+nbfriends+" friends, see <a target='_blank' href='"+osocialurl+"id.php?id="+osocialid+"'>your public page</a>";
					htmlhautcheck += " (<a target='_blank' href='"+osocialurlgraph+"index.php?id="+osocialid+"'>visualization</a>).";			
					htmlhautcheck += "<br>";
			}
			else
			{
					htmlhautcheck = htmlhaut + "You have already an oSocial page with "+nbfriends+" friends, see <a target='_blank' href='"+osocialurl+"id.php?id="+osocialid+"&t="+osocialtoken+"'>your private page</a>";
					htmlhautcheck += " (<a target='_blank' href='"+osocialurlgraph+"index.php?id="+osocialid+"&t="+resultjson.osocialtoken+"'>visualization</a>).";					
					htmlhautcheck += "<br>";					
			}
		}
		else
		{
			if (resultjson.privacy==1) 
			{
					htmlhautcheck = htmlhaut +"<a target='_blank' href='"+osocialurl+"id.php?id="+osocialid+"'>your public oSocial page</a> with "+nbfriends+" friends";
					htmlhautcheck += " (<a target='_blank' href='"+osocialurlgraph+"index.php?id="+osocialid+"'>visualization</a>).";			
					htmlhautcheck += "<br>";
			}
			else
			{
					htmlhautcheck = htmlhaut + "<a target='_blank' href='"+osocialurl+"id.php?id="+osocialid+"&t="+osocialtoken+"'>your private oSocial page</a> with "+nbfriends+" friends";
					htmlhautcheck += " (<a target='_blank' href='"+osocialurlgraph+"index.php?id="+osocialid+"&t="+resultjson.osocialtoken+"'>visualization</a>).";					
					htmlhautcheck += "<br>";
			}					
		}
		dom_div_haut.innerHTML = htmlhautcheck;
        dom_content.appendChild(dom_div_haut);        
			  
//		if (((domain=="hi5.com") && (currentview=="canvas"))||(domain=="orkut.com")||(domain=="opensocket"))
//        {  

			var cbr = document.createElement("br");
			dom_content.appendChild(cbr);   	   
			PrivacyRadioButtonDiv(resultjson.privacy);		
			if (privacy==1)
				dom_button.innerHTML = "Update your public page with your "+nsname+" friends";
			else
				dom_button.innerHTML = "Update your private page with your "+nsname+" friends";												
			dom_button.onclick = PostData(encodeURIComponent(viewername),viewerid,viewerprofile,viewerthumbnail,osocialid,osocialtoken,privacy,registered);                            
			dom_content.appendChild(dom_button);          
		
//		}
//		else
//		{
//			htmlbas +="<p><b>View</b> the application to update your friends</p><br>";
//		}
		  
		if ((currentview=="canvas")	|| (currentview=="preview"))
		{
			htmlbas +="<a href='javascript:void(0);' onclick='javascript:InviteFriends();'>Invite your friends to use oSocial</a>";	
			htmlbas +="<p class='noteremove'><a href=\"javascript:void(0);\" onclick=\"javascript:RemoveProfile("+osocialid+",'"+osocialtoken+"');\">Remove your profile page and leave oSocial.</a></p><br>";	
		}
      }
      else
      {      
              dom_div_haut.innerHTML = htmlhaut + "Not yet in <a target='_blank' href='"+osocialurl+"'>oSocial</a>.<br>";
              dom_content.appendChild(dom_div_haut);        
              
			  var cbr = document.createElement("br");
			dom_content.appendChild(cbr);   	   
			
			//if (((domain=="hi5.com") && (currentview=="canvas"))||(domain=="orkut.com")||(domain=="opensocket"))
			//{  
				PrivacyRadioButtonDiv(1);
				var cbr = document.createElement("br");
				dom_content.appendChild(cbr);   	   
			  
				dom_button.innerHTML = "Create your oSocial page with your "+nsname+" friends and free your Social Graph.";
				dom_button.onclick = PostData(encodeURIComponent(viewername),viewerid,viewerprofile,viewerthumbnail,0,"",0,0);
				dom_content.appendChild(dom_button);         			  
				htmlbas = "";
			 //}
			 //else
			//{
			//	htmlbas = "<p><b>Add and view</b> the application to free your Social Graph</p><br>";
			//}
			  
		if ((currentview=="canvas") || (currentview=="preview"))
		{
			  htmlbas += "<br>Create your oSocial page is <b>the owner responsability</b>. <br>You can set your profile with a <b>Public</b> or a <b>Private</b> privacy policy. <br><b>Private</b> means that only you and your friends will be able to browse it in oSocial Web site and no one else, <b>a secret link</b> will give you access to your private page.<br>";			  
			  htmlbas += "<p class='noteremove'><br>Note that if you set your oSocial page to <b>Public</b> then it will be opened to the Web during 24 hours but in any cases, all your friends are kept private until they decide themself to be public.</p>";
			  htmlbas +="<img src='http://www.osocial.net/network/images/osocial_graph.jpg'>";			  
			  htmlbas += "<br><p class='note'>Free and open your social graph with oSocial <img src='http://www.osocial.net/images/osocial_veryverysmall.png' border='0'></p>";
			  htmlbas +="<a href='javascript:void(0);' onclick='javascript:InviteFriends();'>Invite your friends to use oSocial</a>";	
		}
		else
		{
			  htmlbas += "<br><b>More details on the privay policy in application about and details.</b><br>"			  
			  htmlbas += "<br><p class='note'>Free and open your social graph with oSocial <img src='http://www.osocial.net/images/osocial_veryverysmall.png' border='0'></p>";		
		}
			  
      }       
     
    dom_div_bas.innerHTML = htmlbas;
    
    dom_content.appendChild(dom_div_bas);
        
    },getparams,0);
	
	//if (nsid==2) //hi5
	//{
		if ((currentview=="canvas") || (currentview=="preview"))	
			gadgets.window.adjustHeight(500);
		else
			gadgets.window.adjustHeight(150);
	//}
    	        
};

function PrivacyRadioButtonDiv(iPrivacy) 
{
		debug("PrivacyRadioButtonDiv");
		var rdo1;
		var rdo2;

      try{
        dom_radiobuttondiv = document.createElement('<div class="radiodiv"/>');
      }catch(err){
	   dom_radiobuttondiv = document.createElement('div');
	   dom_radiobuttondiv.setAttribute('class','radiodiv');	   	   
		}		
		
       var dom_text_privacy = document.createTextNode("Your profile privacy policy ");
       dom_radiobuttondiv.appendChild(dom_text_privacy);   
		
      try{
		if (iPrivacy==1)
			rdo1 = document.createElement('<input checked=true type="radio" id="radio_privacy_public" name="radio_privacy"/>');
		else
			rdo1 = document.createElement('<input type="radio" id="radio_privacy_public" name="radio_privacy"/>');
      }catch(err){
        rdo1 = document.createElement('input');
        rdo1.setAttribute('type','radio');
        rdo1.setAttribute('name','radio_privacy');
        rdo1.setAttribute('id','radio_privacy_public');
		if (iPrivacy==1)
			rdo1.setAttribute('checked',true);		
      }
		
      dom_radiobuttondiv.appendChild(rdo1);                                  
      
      var dom_text = document.createTextNode("Public ");              
      dom_radiobuttondiv.appendChild(dom_text);        
                          
      try{
		if (iPrivacy==0)
			rdo2 = document.createElement('<input checked=true type="radio" id="radio_privacy_private" name="radio_privacy" />');
		else
			rdo2 = document.createElement('<input type="radio" id="radio_privacy_private" name="radio_privacy" />');
      }catch(err){
        rdo2 = document.createElement('input');
        rdo2.setAttribute('type','radio');
        rdo2.setAttribute('name','radio_privacy');
        rdo2.setAttribute('id','radio_privacy_private');
		if (iPrivacy==0)
			rdo2.setAttribute('checked',true);
      }

      dom_radiobuttondiv.appendChild(rdo2);
      
      var dom_text = document.createTextNode("Private");              
      dom_radiobuttondiv.appendChild(dom_text);

	  dom_content.appendChild(dom_radiobuttondiv);	  	   
	   
};


function PostData(iusername,iuserid,iprofile,ithumbnail,iosocialid,itoken,iprivacy,iregistered){
		debug("PostData");
        return function() {

      dom_content.removeChild(dom_button);
	  
      var luserprivacy_private_dom=document.getElementById('radio_privacy_private');
      var luserprivacy_public_dom=document.getElementById('radio_privacy_public'); 
            
      if (luserprivacy_private_dom.checked)
        var luserprivacy=0;
      if (luserprivacy_public_dom.checked)
        var luserprivacy=1;

      if (iosocialid==0)
      {  
            /*var postdata = {
                uname : iusername,
                uprofile : iprofile,
                uthumbnail : ithumbnail,
                uid : iuserid,
                nsid : nsid    
            };
            postparams["postData"] = getPOSTString(postdata);*/			

			makeCachedRequest(osocialurldb+'insertuser.php5?uprivacy='+luserprivacy+'&nsid='+nsid+'&uname='+iusername+'&uprofile='+iprofile+'&uthumbnail='+ithumbnail+'&uid='+iuserid,

            function (responseJSON) {         
                                
                var resultjson = responseJSON.data;
				if (resultjson.result=='success') 
				{                				
					var losocialid = resultjson.osocialid; 
					var ltoken = resultjson.osocialtoken;
                
					friendsPost(losocialid,ltoken);
                  
					dom_div_bas.innerHTML = "<p class='progress'>Friends update in progress ...</p>"+htmlbas;
					
					if (resultjson.privacy==0) 
					{
						htmlhaut += "<br>Congratulation, you have now an oSocial page, see <a target='_blank' href='"+osocialurl+"id.php?id="+losocialid+"&t="+osocialtoken+"'>your private page</a>"
						htmlhaut += " (<a target='_blank' href='"+osocialurlgraph+"index.php?id="+losocialid+"&t="+osocialtoken+"'>visualization</a>).";						
						htmlhaut += "<br>";
					}
					else
					{
						htmlhaut += "<br>Congratulation, you have now an oSocial page, see <a target='_blank' href='"+osocialurl+"id.php?id="+losocialid+"'>your public page</a>";
						htmlhaut += " (<a target='_blank' href='"+osocialurlgraph+"index.php?id="+losocialid+"'>visualization</a>).";			
						htmlhaut += "<br>";
					}
					
					postActivity(ownername+" has created an <a href='http://www.osocial.net/network'>oSocial page</a> at " + new Date().toString());
                }                      
				else
				{
					htmlhaut += "<p class='progress'><br>Sorry, you can not create an oSocial page : "+resultjson.raison+"</p><br>";                                                   
				}
				dom_div_haut.innerHTML = htmlhaut;
      
          }, getparams,0);   
      }
      else
      {
          if (iregistered==0)
          {
			makeCachedRequest(osocialurldb+'updateuser.php5?uprivacy='+luserprivacy+'&uname='+iusername+'&uprofile='+iprofile+'&uthumbnail='+ithumbnail+'&osocialid='+iosocialid+'&osocialtoken='+itoken,
			function (responseJSON) {         
                    
                var resultjson = responseJSON.data;
				if (resultjson.result=='success') 
				{                 
                    friendsPost(iosocialid,itoken);       
                     dom_div_bas.innerHTML = "<p class='progress'> Friends update in progress ...</p>"+htmlbas;

					if (luserprivacy==1) 	
					{					
						htmlhaut += "<br>Congratulation, your oSocial page has been created, see <a target='_blank' href='"+osocialurl+"id.php?id="+iosocialid+"'>your public page</a>";
						htmlhaut += " (<a target='_blank' href='"+osocialurlgraph+"index.php?id="+iosocialid+"'>visualization</a>).";			
						htmlhaut += "<br>";						
					}
					else
					{
						htmlhaut += "<br>Congratulation, your oSocial page has been created, see <a target='_blank' href='"+osocialurl+"id.php?id="+iosocialid+"&t="+itoken+"'>your private page</a>";
						htmlhaut += " (<a target='_blank' href='"+osocialurlgraph+"index.php?id="+iosocialid+"&t="+itoken+"'>visualization</a>).";						
						htmlhaut += "<br>";
					}
					postActivity(ownername+" has created an <a href='http://www.osocial.net/network'>oSocial page</a> at " + new Date().toString());
                 }
                  else
                  {
                      dom_div_bas.innerHTML = "<p class='progress'> Can not update your profile : "+resultjson.raison+"</p>"+htmlbas;					  
                      htmlhaut += "<br>";
                  }
				  dom_div_haut.innerHTML = htmlhaut;
      
          }, getparams,0);   
          }
          else
          {
				makeCachedRequest(osocialurldb+'updateuser.php5?nsid='+nsid+'&uname='+iusername+'&uprofile='+iprofile+'&uthumbnail='+ithumbnail+'&uprivacy='+luserprivacy+'&osocialid='+iosocialid+'&osocialtoken='+itoken,
				function (responseJSON) {         
                    
					var resultjson = responseJSON.data;
					if (resultjson.result=='success') 
					{                     
						friendsPost(iosocialid,itoken);              
						dom_div_bas.innerHTML = "<p class='progress'> Friends update in progress ...</p>"+htmlbas;
						
						if (luserprivacy==1) 					 
						{
							htmlhaut = "<br>Check <a target='_blank' href='"+osocialurl+"id.php?id="+iosocialid+"'>your updated public page</a>";
							htmlhaut += " (<a target='_blank' href='"+osocialurlgraph+"index.php?id="+iosocialid+"'>visualization</a>).";			
							htmlhaut += "<br>";							
						}
						else
						{
							htmlhaut = "<br>Check <a target='_blank' href='"+osocialurl+"id.php?id="+iosocialid+"&t="+itoken+"'>your updated private page</a>";
							htmlhaut += " (<a target='_blank' href='"+osocialurlgraph+"index.php?id="+iosocialid+"&t="+itoken+"'>visualization</a>).";						
							htmlhaut += "<br>";
						}
						dom_div_haut.innerHTML = htmlhaut;
					}
					else
					{
                      dom_div_bas.innerHTML = "<p class='progress'> Can not update your profile : "+resultjson.raison+"</p>"+htmlbas;
					}					
      
				}, getparams,0);   
          }      
      } 
      
            
  };      
}; 


function friendsPost(iosocialid,iosocialtoken){ 
	  debug("friendsPost");
		
      var luserprivacy_private_dom=document.getElementById('radio_privacy_private');
      var luserprivacy_public_dom=document.getElementById('radio_privacy_public'); 
            
      if (luserprivacy_private_dom.checked)
        var luserprivacy=0;
      if (luserprivacy_public_dom.checked)
        var luserprivacy=1;

var opt_params = {};
//opt_params[opensocial.DataRequest.PeopleRequestFields.MAX] = 1000;
//fix for friendster
opt_params[opensocial.DataRequest.PeopleRequestFields.MAX] = 500;
opt_params[opensocial.DataRequest.PeopleRequestFields.PROFILE_DETAILS] = [opensocial.Person.Field.PROFILE_URL]; 

var req = opensocial.newDataRequest();

req.add(req.newFetchPeopleRequest('OWNER_FRIENDS', opt_params),'ownerFriends');


req.send(function(dataResponse) {

var owner_friends = dataResponse.get('ownerFriends').getData();    
var ifriend=0;

debug("owner_friends="+dataResponse.get('ownerFriends').getData());
var lnbfriends=owner_friends.getTotalSize();

    owner_friends.each(function(person) { 
				
        fnameinit = person.getDisplayName();
        var fname = encodeURIComponent(person.getDisplayName());
        var fuid = person.getField(opensocial.Person.Field.ID);     
		debug("fnameinit="+person.getDisplayName());

		//if (nsid==3)
		//	var fprofile = encodeURIComponent('http://sandbox.orkut.com' +person.getField(opensocial.Person.Field.PROFILE_URL));
		//else
		var fprofile = encodeURIComponent(person.getField(opensocial.Person.Field.PROFILE_URL));

			var fthumbnail = encodeURIComponent(person.getField(opensocial.Person.Field.THUMBNAIL_URL));
        
        makeCachedRequest(osocialurldb+'addfriend.php5?fprivacy='+luserprivacy+'&osocialtoken='+iosocialtoken+'&osocialid='+iosocialid+'&nsid='+nsid+'&fname='+fname+'&fprofile='+fprofile+'&fthumbnail='+fthumbnail+'&fuid='+fuid,
        function (responseJSON) {        
		
             var resultjson = responseJSON.data;
			if (resultjson.result=='success') 
			{                           
				//ifriend+=1;
				//dom_div_bas.innerHTML = "<p class='progress'> Friend "+fnameinit+" updated ("+ifriend+" / "+lnbfriends+" ).</p>";
            
			}
                        
       },getparams,0);                       
    });

dom_div_bas.innerHTML = "<p class='progress'> All "+lnbfriends+" "+nsname+" friends updated.</p>"+htmlbas;      
postActivity(ownername+" has updated friends list in <a href='http://www.osocial.net/network'>oSocial</a> at " + new Date().toString());

    
});

}

function RemoveProfile(iosocialid,iosocialtoken){
       debug("friendsPost");
		
      dom_content.removeChild(dom_button);
	  dom_content.removeChild(dom_radiobuttondiv);
        
        makeCachedRequest(osocialurldb+'removeuser.php5?nsid='+nsid+'&osocialid='+iosocialid+'&osocialtoken='+iosocialtoken,
        function (responseJSON) {
        
		 var resultjson = responseJSON.data;
		 
		if (resultjson.result=='success') 
		{        
			
			dom_div_haut.innerHTML = "<p class='progress'>Goodbye "+ownername+"</p>";
			dom_div_bas.innerHTML = "You have been removed from the oSocial.";
			postActivity(ownername+" has left <a href='http://www.osocial.net/network'>oSocial</a> at " + new Date().toString());		  
		 }
		 else
		 {
			dom_div_haut.innerHTML = "Can not be removed from oSocial : "+resultjson.raison;
		 }
                                
       }, getparams,0);                       

};

function postActivity(text) { 
  debug("postActivity");

  var params = {};
  params[opensocial.Activity.Field.TITLE] = text;
  var activity = opensocial.newActivity(params);
  activity.setField(opensocial.Activity.Field.STREAM_FAVICON_URL, 'http://www.osocial.net/images/favicon.png');
  opensocial.requestCreateActivity(activity, opensocial.CreateActivityPriority.LOW);
  //to test callback
  //opensocial.requestCreateActivity(activity,opensocial.CreateActivityPriority.LOW,callback);
  
  getActivities()
};        



function InviteFriends() {
	debug("InviteFriends");
	opensocial.requestShareApp("VIEWER_FRIENDS", opensocial.newMessage("Free, Open, Browse and Export your Social Graph with oSocial."));			
}

function callback(response){
		debug("callback activity");
		debug("response had error? "+response.hadError());
		debug("error="+response.getErrorCode());
	}

function getActivities() {
    var req = opensocial.newDataRequest();
    req.add(req.newFetchActivitiesRequest('VIEWER'), 'viewerActivities');
    req.add(req.newFetchActivitiesRequest('VIEWER_FRIENDS'), 'friendActivities');
    req.send(showActivities);
}

function showActivities(dataResponse) {
  var viewerActivities = dataResponse.get('viewerActivities').getData()['activities'];
  var friendActivities = dataResponse.get('friendActivities').getData()['activities'];
  
  debug("dataResponse had error? "+dataResponse.hadError());
  var titleRetrieved = {};
  var favicon = {};
  viewerActivities.each(function(activity) { 
				        titleRetrieved = activity.getField(opensocial.Activity.Field.TITLE);
						favicon = activity.getField(opensocial.Activity.Field.STREAM_FAVICON_URL);
						debug("viewer act title"+titleRetrieved);
						debug("viewer act favicon"+favicon);
						debug("---------------------------------------------------------------");
      				});	
  debug("");
  friendActivities.each(function(activity) { 
				        titleRetrieved = activity.getField(opensocial.Activity.Field.TITLE);
						favicon = activity.getField(opensocial.Activity.Field.STREAM_FAVICON_URL);
						debug("friend act title"+titleRetrieved);
						debug("friend act favicon"+favicon);
      				});	
}